//
//  CityViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/12.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import FMDB

class CityViewController: KMViewController {
    
    fileprivate let cellId = "cityCell"
    
    var cityBlock : ((String)->Void)? //选择城市回调
    
    fileprivate var currentCity = "" //当前城市
    
    fileprivate var dataArray = [CityModel]() //未分类前的数据
    
    fileprivate var cityArray = [[CityModel]]() //分类后的数据
    
    /// 每个 section 的标题
    fileprivate var sectionTitleArray = [String]() //分类数量
    
    fileprivate var tableView : UITableView!
    
    fileprivate var headView : CityHeadView! //头部视图
    
    init(currentCity:String) {
        super.init(nibName: nil, bundle: nil)
        
        self.currentCity = currentCity
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = selectCity
        self.loadDBData()
        createTableView()
    }
    
    //MARK: 创建tableView
    fileprivate func createTableView() {
        
        headView = CityHeadView.init(frame: .init(x: 0, y: 0, width: ScreenW, height: RATIO_H(maxNum: 370)))
        headView.cityDelegate = self
        headView.currentCityView.text = self.currentCity
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.separatorStyle = .none
        tableView.tableHeaderView = headView
        tableView.sectionIndexColor = UIColor.black //右侧索引文字颜色
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CityCell.self, forCellReuseIdentifier: cellId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
    }
    
    //加载数据
    fileprivate func loadDBData() {
        
        //读取文件
        let path = Bundle.main.path(forResource: "cities", ofType: "db")
        //创建执行数据库的类
        let dataBase = FMDatabase.init(path: path)
        //打开数据库
        dataBase.open()
        
        let sql = "select * from city"
        let result = dataBase.executeQuery(sql, withArgumentsIn: [Any]())
        while (result?.next())! {
            let name = result?.object(forColumn: "name") as? String
            let pinyin = result?.object(forColumn: "pinyin") as? String
            let id = result?.object(forColumn: "id") as? Int
            
            let dictionary = ["name":name ?? "","pinyin":pinyin ?? "","id":"\(String(describing: id))"]
            let model = CityModel.setModel(with: dictionary)
            self.dataArray.append(model)
        }
        
        arraySore()
        
    }
    
    //MARK: 数组分类
    fileprivate func arraySore() {
        
        //创建分组对象
        let indexedCollation = UILocalizedIndexedCollation.current()
        // 获得索引数, 这里是27个（26个字母和1个#）
        let indexCount = indexedCollation.sectionTitles.count
        // 每一个一维数组可能有多个数据要添加，所以只能先创建一维数组，到时直接取来用
        for _ in 0..<indexCount {
            
            let array = [CityModel]()
            self.cityArray.append(array)
        }
        
        // 将数据进行分类，存储到对应数组中
        for model in self.dataArray {
            // 根据 model 的 pinyin 判断应该放入哪个数组里
            // 返回值就是在 indexedCollation.sectionTitles 里对应的下标
            
            let sectionNumber = indexedCollation.section(for: model, collationStringSelector: #selector(getter: CityModel.pinyin))
            
            // 添加到对应的数组中
            cityArray[sectionNumber].append(model)
        }
        
        // 对每个已经分类的一维数组里的数据进行排序，如果仅仅只是分类可以不用这步
        for i in 0..<indexCount {
            
            //排序数组
            let sortedCityModelArray = indexedCollation.sortedArray(from: cityArray[i], collationStringSelector: #selector(getter: CityModel.pinyin))
            //替换原来的数组
            cityArray[i] = sortedCityModelArray as! [CityModel]
        }
        
        // 用来保存没有数据的一维数组的下标
        var tempArray = [Int]()
        for (i,array) in cityArray.enumerated() {
            if array.count == 0 {
                tempArray.append(i)
            }else{
                // 给标题数组添加数据
                sectionTitleArray.append(indexedCollation.sectionTitles[i])
            }
        }
        
        //删除没有数据的数组
        for i in tempArray.reversed() {
            cityArray.remove(at: i)
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        
    }

}

extension CityViewController : UITableViewDelegate,UITableViewDataSource {
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitleArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cityArray[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return RATIO_H(maxNum: 40)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? CityCell
        cell?.model = cityArray[indexPath.section][indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
        self.saveVisitCity(cityName: cityArray[indexPath.section][indexPath.row].name!)
        //保存当前城市
        KMTool.setObject(cityArray[indexPath.section][indexPath.row].name!, forEnumKey: .currentCity)
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        
        return sectionTitleArray[section]
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        
       
    }
    
    /// 这是右侧可以点击跳转的控件 title
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        
        return sectionTitleArray
    }
    
    //MARK: 保存拜访城市
    fileprivate func saveVisitCity(cityName:String) {
        
        //移除数组中相同元素
        if self.headView.visitCityView.dataArray.contains(cityName) {
            for i in 0..<self.headView.visitCityView.dataArray.count {
                if self.headView.visitCityView.dataArray[i] == cityName {
                    self.headView.visitCityView.dataArray.remove(at: i)
                    break
                }
                
            }
        }
        
        //最近拜访城市最多不能超过3个
        if self.headView.visitCityView.dataArray.count == 3 {
            
            self.headView.visitCityView.dataArray.removeLast()
            
        }
        
        
        self.headView.visitCityView.dataArray.insert(cityName, at: 0)
        //将数据保存至本地
        KMTool.setObject(self.headView.visitCityView.dataArray, forEnumKey: .city)
        self.headView.visitCityView.collectionView.reloadData()
        
        self.cityBlock!(cityName)
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
}

extension CityViewController : CityHeadViewDelegate {
    
    //MARK: 选择当前城市
    func selectCurrentCity(name: String) {
        self.saveVisitCity(cityName: name)
    }
    
    //MARK: 选择最近拜访城市
    func selectVisitCity(name: String) {
        self.saveVisitCity(cityName: name)
    }
    
    //MARK: 选择热门城市
    func selectPopularCity(name: String) {
        self.saveVisitCity(cityName: name)
    }
    
}




